<template>
  <t-button theme="primary" size="large" @click="onTicket" block>
    {{ plugin.t('info.ticket') }}
  </t-button>
  <Client ref="client" @post="onClient" />
</template>
<script setup>
  import { ref } from 'vue'
  import app from '@/app'
  import index from '../../../index'
  import configStore from '@/plugin/config/store'
  import Client from '@/plugin/client/components/search.vue'
  import orderStore from '../../../store'

  const plugin = index.plugin
  const props = defineProps(['modelValue'])
  const emit = defineEmits(['update:modelValue', 'ok'])
  const client = ref()
  
  const onClient = row => {
    props.modelValue.client_id = row.id
    props.modelValue.client_name = row.name
    props.modelValue.client_data = row
    emit('update:modelValue', props.modelValue)

    ticketPost()
  }

  const onTicket = async () => {
    // 提示是否更新客户
    if(!props.modelValue.client_id) {
      return client.value.open()
    } else {
      return app.confirm({
        theme: 'info',
        header: app.lang.t('common.message'),
        body: plugin.t('message.ticket_client'),
        confirmBtn: {
          theme: 'primary',
          content: app.lang.t('common.ok'),
        }
      }, hide => {
        client.value.open()
        hide()
      }, () => {
        ticketPost()
      })
    }
  }

  // 开票
  const ticketPost = async () => {
    app.confirm({
      theme: 'warning',
      header: app.lang.t('common.message'),
      body: plugin.t('message.ticket_copy'),
      confirmBtn: {
        theme: 'warning',
        content: app.lang.t('common.ok'),
      }
    }, async (hide) => {
      // 填充表单
      const ticket = Object.assign({}, props.modelValue)
      ticket.ticket = 'ticket'
      ticket.code_key = ticket.code
      ticket.code = await configStore.code(ticket.ticket)
      orderStore.copy(ticket).then(res => {
        app.message('success', 'message.' + res.message)
        emit('ok')
      }).catch(err => {
        app.message('error', 'message.error.' + err.message)
      }).finally(() => {
        hide()
      })
      
    })
    
  }

</script>